package controller

import (
	"encoding/json"
	"fmt"
	"gugojudger/judger"
	"gugojudger/utils/ojchannel"
	"gugojudger/utils/ojresult"
	"gugojudger/utils/stringutils"
	"io/ioutil"
	"net/http"
)

type VQuestion struct {
	ID          uint64
	Content     string
	Lang        string
	LimitTime   uint64
	LimitMemory uint64
	Testcase    []judger.TestCase
}

func (param *VQuestion) String() string {
	str := "BeforeJudge\t__JID:" + fmt.Sprintf("%d", param.ID) + "\t__LANG:" + param.Lang + "\t__CONTENT(B64):" + param.Content + "\t__TESTCASE:"
	for i := 0; i < len(param.Testcase); i++ {
		str = str + param.Testcase[i].String()
	}
	str = str + "\t__IOLIMIT(t/m):" + fmt.Sprintf("%d", param.LimitTime) + "/" + fmt.Sprintf("%d", param.LimitMemory)
	return str
}

//victual judge for problem
func handleJudge(resp http.ResponseWriter, req *http.Request) {
	var res = ojresult.NewResult()

	if req.Method != http.MethodPost {
		resp.WriteHeader(http.StatusMethodNotAllowed)
		res.SetMessage(http.StatusMethodNotAllowed, false)
		resJson, _ := json.Marshal(res)
		superChan.C <- ojchannel.FastLog(1, "A bad Request for handleJudge")
		resp.Write(resJson)
	} else {

		defer func() {
			req.Body.Close()
		}()

		con, _ := ioutil.ReadAll(req.Body)

		var param VQuestion

		err := json.Unmarshal(con, &param)

		superChan.C <- ojchannel.FastLog(1, param.String())

		param.Content = stringutils.B64Decoder(param.Content)
		var compiler judger.COMPILER
		switch param.Lang {
		case "C_GCC":
			compiler = judger.C_GCC
			break
		case "C_MINGW":
			compiler = judger.C_MINGW
			break
		default:
			compiler = judger.AFG_IE
			break
		}

		result := judger.JudgerByContent(param.Content, param.Testcase, int64(param.LimitTime), int64(param.LimitMemory), compiler)
		superChan.C <- ojchannel.FastLog(1, result.OJString())
		resJSON, err := json.Marshal(result)
		if err != nil {
			superChan.C <- ojchannel.FastLog(3, "Unmarshal error:"+err.Error())
		}
		resp.Header().Set("content-type", "application/json")
		resp.Write(resJSON)
	}
}
